package org.example.myleet.p724;

public class Solution {
    /**
     * 2 ms
     */
    public int pivotIndex(int[] nums) {
        if (nums.length == 0) {
            return -1;
        }
        //初始化，左侧为0，右侧为从1位置开始的右侧和
        int leftSum = 0, rightSum = 0, idx = 0;
        for (int i=1; i<nums.length; i++) {
            rightSum += nums[i];
        }
        while (idx < nums.length-1) {
            if (leftSum == rightSum) {
                return idx;
            }
            //左边+nums[idx]，右边-nums[idx+1]，如果左侧和等于右侧和，中间索引找到
            leftSum += nums[idx];
            rightSum -= nums[idx+1];
            ++idx;
        }
        if (leftSum == rightSum) {
            return idx;
        }
        //找不到
        return -1;
    }
}
